/**
 * 右固定列
 */
(function($){
    //右固定相关样式设置
    function setCss(jq){
		var opts = $(jq).datagrid('options')
        var datagridPanel = $(jq).parents(".panel.datagrid");
        datagridPanel.find(".datagrid-view1").css({
            left: 'auto',
            right: 0
        }).addClass("datagrid-left");
        datagridPanel.find(".datagrid-view2").css({
            left: 0,
            right: 'auto'
        }).addClass("datagrid-left");
        var width_view1 = datagridPanel.find(".datagrid-view1").width() + opts.scrollbarSize;
        var width_view2 = datagridPanel.find(".datagrid-view2").width() - opts.scrollbarSize;

        datagridPanel.find(".datagrid-view1").width(width_view1);
        datagridPanel.find(".datagrid-view1 .datagrid-header").width(width_view1);
        datagridPanel.find(".datagrid-view1 .datagrid-body").css({
            'overflow-y': 'auto',
            'padding-right': opts.scrollbarSize + 'px',
            'width': width_view1 + 'px'
        });

        datagridPanel.find(".datagrid-view2").width(width_view2);
        datagridPanel.find(".datagrid-view2 .datagrid-header").width(width_view2);
        datagridPanel.find(".datagrid-view2 .datagrid-body").css({
            'padding-right': 0,
            'overflow-y': 'hidden',
            'overflow-x': 'auto',
            'width': width_view2 + 'px'
        });
        var target = datagridPanel.find(".datagrid-view2 .datagrid-body")[0];
        //变量windowWidth是可视区的宽度
        var windowWidth = target.clientWidth;
        //变量scrollWidth是滚动条的总宽度
        var scrollWidth = target.scrollWidth;
        if(scrollWidth > windowWidth){
			datagridPanel.find(".datagrid-body").unbind("mouseenter");
            datagridPanel.find(".datagrid-body").bind('mouseenter', function (e) {
                e.preventDefault();
                e.stopPropagation();
				var bodyItem = datagridPanel.find(".datagrid-view2 .datagrid-body")[0];
				datagridPanel.find(".datagrid-view1 .datagrid-body-inner").css("padding-bottom",(bodyItem.offsetHeight - bodyItem.clientHeight - 1) + "px");
                return false;
            });
            datagridPanel.find(".datagrid-view1 .datagrid-body-inner").css("padding-bottom","0");
        } else {
            datagridPanel.find(".datagrid-view1 .datagrid-body-inner").css("padding-bottom","0");
        }
    }

    function addEvent(target1,target2,boo,target1_header,target2_header,timer1,timer2){
        target1.scroll(function () {
            if(timer1 != null) clearTimeout(timer1);
            // 解除滚动监听事件，否则两个滚动条一起监听，会导致互相影响
            target2.unbind("scroll mousewheel touchmove");
            // 禁止另外一个滚动条滚动，只有在下面定时器绑定事件后才允许滚动
            target2.bind('scroll mousewheel touchmove', function (e) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            });
            var left = target1.scrollLeft(),
                top = target1.scrollTop();
            target1_header.scrollLeft(left);
            target2.scrollTop(top);

            timer1 = setTimeout(function () {
                target2.unbind('scroll mousewheel touchmove');
                addEvent(target2,target1,boo,target2_header,target1_header,timer2,timer1);
            }, 500);
        });
        target1.bind("mousewheel",function (e){
            var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
                (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));              // firefox
            var target = target1[0];
            //变量scrollTop是滚动条滚动时，距离顶部的距离
            var scrollTop = target.scrollTop + (-delta * 100);
            //变量windowHeight是可视区的高度
            var windowHeight = target.clientHeight;
            //变量scrollHeight是滚动条的总高度
            var scrollHeight = target.scrollHeight;

            //滚动条到底部的条件
            if(scrollTop + windowHeight >= scrollHeight){
                scrollTop = scrollHeight - windowHeight;
            } else if(scrollTop < 0) {
                scrollTop = 0;
            }

            target1.scrollTop(scrollTop);
            // target2.scrollTop(scrollTop);
        });
    }

    //右固定相关相关滚动事件处理
    function setScroll(jq){
        var datagridPanel = $(jq).parents(".panel.datagrid"),
            view1_body = datagridPanel.find(".datagrid-view1 .datagrid-body"),
            view2_body = datagridPanel.find(".datagrid-view2 .datagrid-body"),
            view1_header = datagridPanel.find(".datagrid-view1 .datagrid-header"),
            view2_header = datagridPanel.find(".datagrid-view2 .datagrid-header"),
            timer1 = null,timer2 = null;
        addEvent(view1_body,view2_body,$(jq).data('treegrid'),view1_header,view2_header,timer1,timer2);
        addEvent(view2_body,view1_body,$(jq).data('treegrid'),view2_header,view1_header,timer2,timer1);
    }
    var methods = {
        /**
         * 有固定列
         */
        rightFixed : function(jq) {
            return jq.each(function(){
				var opts = $(this).datagrid('options'),boo = false;
				if(Array.isArray(opts.frozenColumns)) {
				    for(var i = 0, item; item = opts.frozenColumns[i++];) {
				        if(Array.isArray(item) && item.length > 0) {
				            boo = true;
				            break;
				        }
				    }
				}
				if(opts.isRightFixed && opts.frozenColumns && boo){
					setCss(this);
					setScroll(this);
				}
            });
        }
    };
    $.extend($.fn.datagrid.methods, methods);
    $.extend($.fn.treegrid.methods, methods);
    var option = {
        isRightFixed: false,
        onLoadSuccess: function(){
			$(this).datagrid('rightFixed');
        },
        onResizeColumn: function(field, width){
            $(this).datagrid('rightFixed');
        }
    };
    $.extend($.fn.datagrid.defaults, option);
    $.extend($.fn.treegrid.defaults, option);
})(jQuery);
/**
 * 表格模糊查询处理特殊控件查询
 */
(function($){
    function getPluginName(target){
        if ($(target).data('treegrid')){
            return 'treegrid';
        } else {
            return 'datagrid';
        }
    }
    var extendedOptions = {
        defaultFilterOptions: {
            onInit: function(target){
                var name = getPluginName(target);
                var opts = $(target)[name]('options');
                var filterOpts = this.filterOptions;
                var field = $(this).attr('name');
                var input = $(this);
				input.focus(function(){
					nowFilterTable = target;
				});
                var control = $(this);
                var control_optsMode =  true;
                if(filterOpts.type == 'combo' || filterOpts.type == 'combobox' || filterOpts.type == 'combotree' || filterOpts.type == 'combogrid' || filterOpts.type == 'combotreegrid'){
                    var control_opts = control[filterOpts.type]('options');
                    var onClick = null;
                    var onChange=null;
                    var filter = null;
                    if(control_opts.mode){
                        control_optsMode = false;
                    }
                    if(typeof control_opts.onClick == 'function'){
                        onClick = control_opts.onClick;

                    }
                    if(typeof control_opts.onChange == 'function'){
                        onChange = control_opts.onChange;

                    }
                    if(typeof control_opts.filter == 'function'){
                        filter = control_opts.filter;

                    }
                    control[filterOpts.type]({
                        onClick: function(newValue, oldValue){
                            nowFilterTable = target;
                            if(typeof onClick == 'function') {
                                onClick.call(control,newValue, oldValue);
                            }
                        },
                        onChange: function(newValue, oldValue){
                            nowFilterTable = target;
							
							if (this.timer){
							    clearTimeout(this.timer);
							}
							if (opts.filterDelay){
							    this.timer = setTimeout(function(){
							        _doFilter();
							    }, opts.filterDelay);
							} else {
							    _doFilter();
							}
                            if(typeof onChange == 'function') {
                                onChange.call(control,newValue, oldValue);
                            }
                        },
                        filter:function(q, row){
                            var opts = control.combobox('options');
                            return row[opts.textField].indexOf(q)!= -1 ;
                        }
                    });
                    control.parent().find("input[type='text']").bind('keydown.filter',function (e) {
                        $(target)[name]('doFilter');
                    })
                } else if(filterOpts.type == 'datebox' || filterOpts.type == 'datetimebox') {
					var control_opts = control[filterOpts.type]('options');
					var onChange=null;
					var filter = null;
					if(control_opts.mode){
					    control_optsMode = false;
					}
					if(typeof control_opts.onChange == 'function'){
					    onChange = control_opts.onChange;
					
					}
					if(typeof control_opts.filter == 'function'){
					    filter = control_opts.filter;
					
					}
					control[filterOpts.type]({
					    onChange: function(newValue, oldValue){
							nowFilterTable = target;
							if (this.timer){
								clearTimeout(this.timer);
							}
							if (opts.filterDelay){
								this.timer = setTimeout(function(){
									_doFilter();
								}, opts.filterDelay);
							} else {
								_doFilter();
							}
					        if(typeof onChange == 'function') {
					            onChange.call(control,newValue, oldValue);
					        }
					    }
					});
				}
                if (input.data('textbox')){
                    input = input.textbox('textbox');
                }
                if(filterOpts.options && filterOpts.options.value){
                    $(target)[name]('addFilterRule', {
                        field: field,
                        //op: op,
                        value: filterOpts.options.value
                    });
                }
                input.unbind('.filter').bind('input.filter keydown', function(e){
                    nowFilterTable = target;
                    if(control_optsMode) {
                        var t = $(this);
                        if (this.timer) {
                            clearTimeout(this.timer);
                        }
                        if (e.keyCode == 13) {
                            _doFilter();
                        } else if (opts.filterDelay) {
                            this.timer = setTimeout(function () {
                                _doFilter();
                            }, opts.filterDelay);
                        }
                    }
                });
                function _doFilter(){
                    var rule = $(target)[name]('getFilterRule', field);
                    var value;
                    if(filterOpts.type == 'text' || filterOpts.type == 'textbox'|| filterOpts.type == 'numberbox'){
                        value = input.val();
						if(typeof value == "object") value = control[filterOpts.type]("getValue");
                    } else {
                        value = control[filterOpts.type]("getValue");
                    }
                    if (value != '') {
                        if ((rule && rule.value != value) || !rule) {
                            var op = rule ? rule.op : (filterOpts ? filterOpts.defaultFilterOperator || opts.defaultFilterOperator : opts.defaultFilterOperator);
                            $(target)[name]('addFilterRule', {
                                field: field,
                                // op: opts.defaultFilterOperator,
                                op: op,
                                value: value
                            });
                            if(opts.automaticPolling !== false)
                                $(target)[name]('doFilter');
                        }
                    } else {
                        if (rule) {
                            $(target)[name]('removeFilterRule', field);
                            if(opts.automaticPolling !== false)
                                $(target)[name]('doFilter');
                        }
                    }
                }
            }
        }
    };
    $.extend($.fn.datagrid.defaults, extendedOptions);
    $.extend($.fn.treegrid.defaults, extendedOptions);
})(jQuery);
/**
 * 日期控件添加清空功能
 */
(function ($) {
    $.fn.datebox.defaults.editable = false;
    $.fn.datebox.defaults.buttons.splice(1, 0, {
        text: '清空',
        handler: function (target) {
            $(target).datebox('setValue', '').datebox('hidePanel');
        }
    });
})(jQuery);
/**
 * 下拉框面板高度设置
 */
(function ($) {
    $.fn.combo.defaults.panelMaxHeight = '250px';
    $.fn.combo.defaults.panelHeight = 'auto';

    $.fn.combobox.defaults.panelMaxHeight = '250px';
    $.fn.combobox.defaults.panelHeight = 'auto';

    $.fn.combotree.defaults.panelMaxHeight = '250px';
    $.fn.combotree.defaults.panelHeight = 'auto';
})(jQuery);
/**
 * form表单验证方法重写
 */
(function ($) {
	function validate(jq){
		if($.fn.validatebox){
			jq.find(".validatebox-text:not(:disabled)").attr("_isConboboxValidate","true");
			jq.find(".validatebox-text:not(:disabled)").validatebox("validate");
			var _66d = jq.find(".validatebox-invalid");
			_66d.filter(":not(:disabled)").attr("_isValidate","true");
			_66d.filter(":not(:disabled)").mouseenter();
			return _66d.length==0;
		}
		return true;
	}
    $.fn.form.methods.validate = function(jq,isvilid) {
        var boo = validate(jq);
        if(boo && isvilid){
            boo = false;
            var data = jq.serializeArray() || [];
            for (var i = 0; i < data.length; i++) {
                if(data[i].value){
                    var input = jq.find("[name='" + data[i].name + "']");
                    if(input.hasClass("textbox-value") || (input.next().length > 0 && input.next().hasClass("textbox"))){
                        boo = true;
                        break;
                    }
                }
            }
            if(!boo) {
                $.messager.alert("提示", '表单没有填写数据', "warning");
            }
        }
        return boo;
    };
	$.fn.form.methods.readonly = function(jq,readonly){
		var data = jq.serializeArray() || [];
		for (var i = 0; i < data.length; i++) {
			var input = jq.find("[textboxname='" + data[i].name + "']");
			if(input.length > 0){
				input.each(function(){
					var state = $.data(this);
					for(var key in state){
						if(state[key].options) {
							$(this)[key]("readonly",readonly);
						}
					}
				})
			}
		}
	}
})(jQuery);

//控件验证
(function($) {
	function _3(_4) {
		var _5 = $.data(_4, "validatebox");
		_5.validating = false;
		if (_5.vtimer) {
			clearTimeout(_5.vtimer);
		}
		if (_5.ftimer) {
			clearTimeout(_5.ftimer);
		}
		if(_5.options.isTooltip){
			$(_4).tooltip("destroy");
		} else if(_5.options.errTarget){
			_5.options.errTarget.remove();
		}
		$(_4)._unbind();
		$(_4).remove();
	};

	function _19(_1a, _1b, _1c) {
		var _1d = $.data(_1a, "validatebox");
		var _1e = _1d.options;
		var t = $(_1a);
		if(_1e.isTooltip){
			if (_1c == "hide" || !_1b) {
				t.tooltip("hide");
				$(_1a).parents(".textbox").removeClass("validate-error");
			} else {
				if ((t.is(":focus") && _1d.validating) || _1c == "show") {
					t.tooltip($.extend({}, _1e.tipOptions, {
						content: _1b,
						position: _1e.tipPosition,
						deltaX: _1e.deltaX,
						deltaY: _1e.deltaY
					})).tooltip("show");
					$(_1a).parents(".textbox").addClass("validate-error");
				}
			}
		} else {
			if ((_1c == "hide" || !_1b) && _1e.errTarget && _1d.validating) {
				_1e.errTarget.hide();
				$(_1a).parents(".textbox").removeClass("validate-error");
			} else {
				if ((t.is(":focus") && _1d.validating) || _1c == "show") {
					if(_1e.errTarget){
						_1e.errTarget.html(_1b).show();
					} else {
						_1e.errTarget = $("<div style='color: red;font-size: 12px;'>" + _1b + "</div>").appendTo(t.parent().parent());
					}
					if(!_1b){
						$(_1a).parents(".textbox").removeClass("validate-error");
					} else {
						$(_1a).parents(".textbox").addClass("validate-error");
					}
				}
			}
		}
	};
	
	$.fn.validatebox.methods.destroy = function(jq) {
		return jq.each(function() {
			_3(this);
		});
	};
	$.fn.validatebox.parseOptions = function(_3d) {
		var t = $(_3d);
		return $.extend({}, $.parser.parseOptions(_3d, ["validType", "missingMessage", "invalidMessage",
			"tipPosition", {
				delay: "number",
				interval: "number",
				deltaX: "number"
			}, {
				editable: "boolean",
				validateOnCreate: "boolean",
				validateOnBlur: "boolean"
			}
		]), {
			required: (t.attr("required") ? true : undefined),
			disabled: (t.attr("disabled") ? true : undefined),
			readonly: (t.attr("readonly") ? true : undefined),
			novalidate: (t.attr("novalidate") != undefined ? true : undefined),
			isTooltip: (t.attr("isTooltip") != undefined ? true : undefined)
		});
	};
	
	$.fn.validatebox.defaults.isTooltip = false;
	$.fn.validatebox.defaults.errTarget = null;
	var _plugins = ["textbox", "passwordbox", "maskedbox", "filebox", "combo", "combobox",
	"combotree", "combogrid", "combotreegrid", "tagbox", "numberbox", "validatebox", "searchbox",
	"spinner", "numberspinner", "timespinner", "datetimespinner", "datebox","datetimebox", 
	"timepicker"];
	for(var i = 0; i < _plugins.length; i++){
		if($.fn[_plugins[i]].defaults.err){
			$.fn[_plugins[i]].defaults.err = function(_3f,_40,_41){
				var target = $(_3f);
				if(target.attr("_isValidate")){
					_19(_3f,_40,_41);
				}
			}
		}
	}
	
	var _comboValFun = $.fn.combo.methods.setValue;
	$.fn.combo.methods.setValue = function(jq, _59){
		// debugger;
		_$vilidate(jq, _59);
		_comboValFun(jq, _59);
	}
	var _comboValsFun = $.fn.combo.methods.setValues;
	$.fn.combo.methods.setValues = function(jq, _58){
		// debugger;
		_$vilidate(jq, _58);
		_comboValsFun(jq, _58);
	}
	$.fn.combo.defaults.isValidateVal = false;
	function _$vilidate(jq,value){
		if($.fn.validatebox){
			var state = $.data(jq[0],"combo");
			var boo = false;
			if(Array.isArray(value)) {
				if(value.length > 1 || (value.length > 0 && value[0])) {
					boo = true;
				}
			} else if(value) {
				boo = true;
			}
			if(state.options.isValidateVal || boo){
				$(jq).next().find(".validatebox-text:not(:disabled)").validatebox("validate");
				$(jq).next().find(".validatebox-text:not(:disabled)").mouseenter();
			} else {
				state.options.isValidateVal = true;
			}
		}
	}
})(jQuery);

/**
 * form表单提交类路径属性处理
 */
(function($){
	var form = $.fn.form,
	submitFn = $.fn.form.methods.submit;
	fomatVal = function (param){
		if(param) param = App.delProperty(param,"@type",Infinity);
		// var formData = $(this).serializeArray(),obj = {};
		// if(formData) {
		// 	for(var i = 0; i < formData.length; i++) {
		// 		obj[formData[i].name] = formData[i].value;
		// 	}
		// 	obj = App.delProperty(obj,"@type",Infinity);
		// 	$(this).form("load",obj)
		// }
	};
	$.fn.form = function(options, param){
		if (typeof options == "object") {
			var onSubmit = options.onSubmit;
			options.onSubmit = function(pramas){
				var res = true;
				if(onSubmit) res = onSubmit.call(this,pramas);
				else res = $(this).form("validate");
				fomatVal.call(this,pramas);
				return res
			}
		}
		return form.call(this,options, param);
	}
	$.fn.form = Object.assign($.fn.form,form);
	$.fn.form.methods.submit = function(jq,pramas){
		if(pramas && pramas.onSubmit){
			var onSubmit = pramas.onSubmit;
			pramas.onSubmit = function(pramas){
				var res = onSubmit.call(this,pramas);
				fomatVal.call(this,pramas);
				return res;
			}
		}
		return submitFn.call(this,jq,pramas);
	}
})(jQuery);
/**
 * 提示弹窗修改
 */
(function ($) {
	var $alert = $.messager.alert;
	$.messager.alert = function(_13, msg, _14, fn){
		if(!_13) _13 = '提示';
		var result = $alert(_13, msg, _14, fn);
		return result;
	}
	
	var $confirm = $.messager.confirm;
	$.messager.confirm = function(_16, msg, fn){
		if(!_16) _16 = '提示';
		var result = $confirm(_16, msg, fn);
		return result;
	}
	
	var $prompt = $.messager.prompt;
	$.messager.prompt = function(_18, msg, fn){
		if(!_18) _18 = '提示';
		var result = $prompt(_18, msg, fn);
		return result;
	}
})(jQuery);
/**
 * datagrid 重写固定的计算
 */
(function ($) {
    var $relocation = $.fn.datagrid.methods.fixColumnSize;
    $.fn.datagrid.methods.fixColumnSize = function(jq, _8c1){
        var result = $relocation(jq, _8c1);
        $(jq).datagrid('rightFixed');
        return result;
    }
})(jQuery);
/**
 * 常规表格删除数据后，序号重新排序
 */
(function($){
	var deleteRow = $.fn.datagrid.methods.deleteRow;
	$.fn.datagrid.methods.deleteRow = function(jq,_8db){
		var result = deleteRow(jq,_8db);
		jq.each(function(){
			var data = $(this).datagrid("getRows");
			for(var i = 0; i < data.length; i++) {
				var editors = $(this).datagrid("getEditors", i);
				if(editors.length){
					var obj = [];
					for(var j = 0; j < editors.length; j++) {
						var ed = editors[j];
						obj.push(ed.actions.getValue(ed.target));
					}
					$(this).datagrid("refreshRow",i);
					$(this).datagrid("beginEdit",i);
					editors = $(this).datagrid("getEditors", i);
					for(var j = 0; j < editors.length; j++) {
						var ed = editors[j];
						ed.actions.setValue(ed.target, obj[j]);
					}
				} else {
					$(this).datagrid("refreshRow",i);
				}
			}
		});
		return result;
	}
})(jQuery);
/**
 * 常规表格重新加载表格后去除之前勾选项
 */
(function($){
	var load = $.fn.datagrid.methods.load;
	$.fn.datagrid.methods.load = function(jq,_8bb){
		jq.each(function(){
			$(this).datagrid("clearSelections");
			$(this).datagrid("clearChecked");
		});
		var result = load(jq,_8bb);
		return result;
	}
	var load_treegrid = $.fn.treegrid.methods.load;
	$.fn.treegrid.methods.load = function(jq,_8bb){
		jq.each(function(){
			$(this).treegrid("clearSelections");
			$(this).treegrid("clearChecked");
		});
		var result = load_treegrid(jq,_8bb);
		return result;
	}
})(jQuery);

/**
 * 日期控件禁止选择某个日期
 */
(function($){
	var showPanel = $.fn.combo.methods.showPanel;
	$.fn.combo.methods.showPanel = function(jq){
		setCalendar(jq);
		return showPanel(jq);
	}
	function setCalendar(jq){
		if ($(jq).data('datebox')){
			var opt = $(jq).datebox("options");
			var c = $(jq).datebox("calendar");
            var copt = c.calendar("options");
            var validator = copt.validator;
			c.calendar({
				validator: function(date){
                    var boo = opt.disabledDate ? opt.disabledDate.call(jq[0],date) : true;
                    if(validator && typeof validator == "function") {
                        return boo && validator(date);
                    } else {
                        return boo;
                    }
				}
			});
		}
	}
})(jQuery);
/**
 * 表格页面信息存储
 */
(function($){
	function optionSet(options){
		if (typeof options == "string" || !options) return;
		var loader,storageKey = "table_" + $(this).attr("id") + window.location.pathname;
		if(options.loader){
			loader = options.loader;
			options.loader = function(data,successfn,errorfn){
				window.localStorage.setItem(storageKey,JSON.stringify({
					page: data.page,
					rows: data.rows,
				}));
				loader.call(this,data,successfn,errorfn);
			};
		} else {
			options.loader = function(data,successfn,errorfn){
				window.localStorage.setItem(storageKey,JSON.stringify({
					page: data.page,
					rows: data.rows,
				}));
				var opts;
				if ($(this).data('treegrid')){
				    opts = $(this).treegrid("options");
				} else {
				    opts = $(this).datagrid("options");
				}
				if(!opts.url){
					return false;
				}
				$.ajax({type:opts.method,url:opts.url,data:data,dataType:"json",success:function(data){
						successfn(data);
					},error:function(){
						errorfn.apply(this,arguments);
					},
				});
			}
		}
		var pageInfo = window.localStorage.getItem(storageKey);
		if(pageInfo) {
			try{
				pageInfo = JSON.parse(pageInfo);
				if(pageInfo.page) options.pageNumber = pageInfo.page;
				if(pageInfo.rows) options.pageSize = pageInfo.rows;
			} catch(e){
				
			}
		}
	}
	var datagrid = $.fn.datagrid;
	$.fn.datagrid = function(options, param){
		optionSet.call(this,options);
		return datagrid.call(this,options, param);
	}
	$.fn.datagrid = Object.assign($.fn.datagrid,datagrid);
	
	var treegrid = $.fn.treegrid;
	$.fn.treegrid = function(options, param){
		optionSet.call(this,options);
		return treegrid.call(this,options, param);
	}
	$.fn.treegrid = Object.assign($.fn.treegrid,treegrid);
})(jQuery);
/**
 * number控件 显示在小数点后面的最大精度。取值优化
 */
(function ($) {
	// 四舍五入保留2位小数（不够位数，则用0替补）
	function keepTwoDecimalFull(val,precision) {
		var s = parseFloat(val);
		if (isNaN(s)) {   
			return NaN;  
		}
		precision = precision < 0 ? 0 : precision;
		val += "";
		var pp = val.indexOf(".")
		if(pp > 0) {
			var inte = val.substring(0,pp);
			if(precision){
				var deci = val.substring(pp + 1,pp + precision + 2),
					len = precision - deci.length;
				//位数不够进行补位
				if(len > -1) {
					for(var i = -1; i < len; i++) {
						deci += '0';
					}
				}
				//获取小数最后两位
				var n1 = parseInt(deci[deci.length - 2]),
					n2 = parseInt(deci[deci.length - 1]);
				//根据最后一位小数进行四舍五入
				if(n2 >= 5){
					n1 += 1;
				}
				return inte + "." + deci.substring(0,deci.length - 2) + n1;
			} else {
				return inte;
			}
		} else {
			return val;
		}
	}
	
    $.fn.numberbox.defaults.parser = function(s){
		s = s + "";
		var _1d = $(this).numberbox("options");
		if (_1d.prefix) {
			s = $.trim(s.replace(new RegExp("\\" + $.trim(_1d.prefix), "g"), ""));
		}
		if (_1d.suffix) {
			s = $.trim(s.replace(new RegExp("\\" + $.trim(_1d.suffix), "g"), ""));
		}
		if (parseFloat(s) != _1d.value) {
			if (_1d.groupSeparator) {
				s = $.trim(s.replace(new RegExp("\\" + _1d.groupSeparator, "g"), ""));
			}
			if (_1d.decimalSeparator) {
				s = $.trim(s.replace(new RegExp("\\" + _1d.decimalSeparator, "g"), "."));
			}
			s = s.replace(/\s/g, "");
		}
		var val = keepTwoDecimalFull(s,_1d.precision);
		if (isNaN(val)) {
			val = "";
		} else {
			if (typeof(_1d.min) == "number" && val < _1d.min) {
				val = keepTwoDecimalFull(_1d.min,_1d.precision);
			} else {
				if (typeof(_1d.max) == "number" && val > _1d.max) {
					val = keepTwoDecimalFull(_1d.max,_1d.precision);
				}
			}
		}
		return val;
	}
})(jQuery);
/**
 * 判断表格是否自动扩大或缩小列的尺寸以适应网格的宽度并且防止水平滚动
 */
(function ($) {

		// var onResizeColumn = opts.onResizeColumn;
	function isFitColumns(options, isResize){
		if(typeof options == "string" || !options || !$(this).parent()[0]) return;
		var width1 = parseFloat($(this).parent()[0].style.width),
			width2 = $(this).parent().width(),
			width = width1 > width2 ? width1 : width2,countH = 0;
		if(options.frozenColumns && Array.isArray(options.frozenColumns) && options.frozenColumns[0] && Array.isArray(options.frozenColumns[0])){
			options.frozenColumns[0].forEach(function(column){
				if(typeof column.width == "string" && column.width.indexOf("%") != -1){
					countH += parseFloat(column.width) / 100 * width;
				} else if(typeof column.width == "string" && column.width.indexOf("px") != -1){
					countH += parseFloat(column.width);
				} else if(typeof column.width == "number"){
					countH += column.width;
				} else {
					column.width = 100;
					countH += column.width;
				}
			});
		}
		if(options.columns && Array.isArray(options.columns) && options.columns[0] && Array.isArray(options.columns[0])){
			options.columns[0].forEach(function(column){
				if(typeof column.width == "string" && column.width.indexOf("%") != -1){
					countH += parseFloat(column.width) / 100 * width;
				} else if(typeof column.width == "string" && column.width.indexOf("px") != -1){
					countH += parseFloat(column.width);
				} else if(typeof column.width == "number"){
					countH += column.width;
				} else {
					column.width = 100;
					countH += column.width;
				}
			});
		}
		// if(isResize && options.fitColumns != width > countH) {
		// 	options.fitColumns = width > countH;
		// 	$(this).datagrid(options);
		// }
		options.fitColumns = width > countH;
		// else
	}

	var resize = $.fn.datagrid.methods.resize;
	$.fn.datagrid.methods.resize = function(jq, param){
        var options=$.data(jq[0],"datagrid").options;
		isFitColumns.call(jq[0],options, true);
		var res = resize.call(this, jq, param);
		return res;
	}

	var datagrid = $.fn.datagrid;
	$.fn.datagrid = function(options, param){
		isFitColumns.call(this,options, false);
		return datagrid.call(this,options, param);
	}
	$.fn.datagrid = Object.assign($.fn.datagrid,datagrid);
})(jQuery);

/**
 * 数据网格详细视图 展开或收起时，避免冒泡调用行相关事件
 */
(function ($) {
	if(detailview) {
		$.extend(detailview,{
			bindEvents: function(target){
				var state = $.data(target, 'datagrid');
				if (state.ss.bindDetailEvents){return;}
				state.ss.bindDetailEvents = true;
				var dc = state.dc;
				var opts = state.options;
				var body = dc.body1.add(dc.body2);
				var clickHandler = ($.data(body[0],'events')||$._data(body[0],'events')).click[0].handler;
				body.off('click.detailview',".datagrid-row-expander").on('click.detailview', ".datagrid-row-expander",function(e){
					var tt = $(e.target);
					var tr = tt.closest('tr.datagrid-row');
					if (!tr.length){return}
					if (tt.hasClass('datagrid-row-expander')){
						var rowIndex = parseInt(tr.attr('datagrid-row-index'));
						if (tt.hasClass('datagrid-row-expand')){
							$(target).datagrid('expandRow', rowIndex);
						} else {
							$(target).datagrid('collapseRow', rowIndex);
						}
						$(target).datagrid('fixRowHeight');
						e.stopPropagation();
					} else {
						// clickHandler(e);
					}
				}).off('dblclick.detailview',".datagrid-row-expander").on('dblclick.detailview',".datagrid-row-expander",function(e){
					e.stopPropagation();
				});
			},
		});
	}
})(jQuery);

/**
 * 进度条上的文字显示
 */
(function ($) {
	
	//重写进度条赋值方法
	$.extend($.fn.progressbar.defaults,{
		// isInit: true,//是否是初始化赋值
		isShowProgress: true,//是否显示进度
		showContent: null,//进度显示
	})
	$.extend($.fn.progressbar.methods,{
		/**
		 * 重写进度条赋值方法
		 * @param {Object} jq
		 * @param {Object} _e
		 */
		setValue: function(jq, progress) {
			if (progress < 0) {
				progress = 0;
			}
			if (progress > 100) {
				progress = 100;
			}
			return jq.each(function() {
				var opts = $.data(this, "progressbar").options;
				var val = opts.value;
				opts.value = progress;
				// if(opts.isInit){
				// 	opts.isInit = false;
				// } else {
				// 	$(this).find("div.progressbar-value").css("transition","width .1s linear");
				// }
				$(this).find("div.progressbar-value").width(progress + "%");
				if(opts.isShowProgress) {
					var showText;
					if(opts.showContent && typeof opts.showContent == "function"){
						showText = opts.showContent(progress, val);
					}
					if(!showText) {
						showText = opts.text.replace(/{value}/, progress);
					}
					$(this).find("div.progressbar-text").html(showText);
				}
				
				if (val != progress) {
					opts.onChange.call(this, progress, val);
				}
			});
		}
	})
})(jQuery);
/**
 * 表格行编辑，实时显示值
 */
(function ($) {
    function getPluginName(target){
        if ($(target).data('treegrid')){
            return 'treegrid';
        } else {
            return 'datagrid';
        }
    }
	function showContentByTitle(jq,index){
		var pluginFn = $(jq)[getPluginName(jq)];
		var editors = pluginFn.call(jq,"getEditors",index);
		
		
		editors.forEach(function(ed){
			var titleSpan,watchInput;
			var opts = $(ed.target)[ed.type]("options");
			var ed_val;
			if(opts.multiple){
				ed_val = $(ed.target)[ed.type]("getValues")
			} else {
				ed_val = $(ed.target)[ed.type]("getValue")
			}
			var onChange = opts.onChange;
			opts.onChange = function(){
				var res = onChange.apply(this,arguments);
				if(titleSpan && watchInput)titleSpan.attr("title",$(watchInput).val());
				return res;
			}
			$(ed.target)[ed.type](opts);
			if(opts.multiple){
				$(ed.target)[ed.type]("setValues",ed_val)
			} else {
				$(ed.target)[ed.type]("setValue",ed_val)
			}
			
			titleSpan = $(ed.target).next();
			watchInput = titleSpan.find(".textbox-text")[0]
			var initVal = $(watchInput).val();
			titleSpan.attr("title",initVal);
			$(watchInput).on("input porpertychange",function(){
				titleSpan.attr("title",$(this).val());
			});
		})
	}
	var datagrid_beginEdit = $.fn.datagrid.methods.beginEdit;
	$.fn.datagrid.methods.beginEdit = function(jq,index){
		var res = datagrid_beginEdit.call(this,jq,index);
		showContentByTitle(jq,index);
		return res;
	}
})(jQuery);